<template>
  <div style="width: 100%; height: 100%; overflow: auto">
    <!-- <div
      style="
        width: 100%;
        /* background-color: #fff; */
        padding: 20px 20px 0;
        border-radius: 5px;
      "
    > -->
      <!-- 搜索 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="formInline.user"
            placeholder="角色名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="reset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    <!-- </div> -->
    <!-- 表格 -->
    <el-card style="width: 100%; margin-top: 15px">
      <template #header>
        <div class="card-header">
          <el-button type="success" :icon="Plus" @click="adds">
            新增
          </el-button>
          <el-button
            type="danger"
            :icon="Delete"
            :disabled="isdel"
            @click="delall"
          >
            删除
          </el-button>
        </div>
      </template>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" width="120" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
              {{ scope.row.status == 1 ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column fixed="right" label="操作" width="280">
          <template #default="scope">
            <el-button
              link
              type="primary"
              :icon="Position"
              @click="fenpei(scope.row)"
            >
              分配权限
            </el-button>
            <el-button
              link
              type="primary"
              :icon="Edit"
              @click="edits(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              :icon="Delete"
              @click="del(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="currentPage4"
        :page-size="pageSize4"
        :page-sizes="[5, 10, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tablenum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="padding: 15px 15px 0"
      />
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="formtitle"
      width="500"
      @close="cancel"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <!-- 输入 -->
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <!-- 输入 -->
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="ruleForm.code" placeholder="请输入角色编码" />
        </el-form-item>
        <!-- 下拉框 -->
        <el-form-item label="数据权限" prop="dataScope">
          <el-select v-model="ruleForm.dataScope" placeholder="请选择">
            <el-option label="所有数据" value="0" />
            <el-option label="部门及子部门数据" value="1" />
            <el-option label="本部门数据" value="2" />
            <el-option label="本人数据" value="3" />
          </el-select>
        </el-form-item>
        <!-- 单选 -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio value="1">正常</el-radio>
            <el-radio value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 排序 -->
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="ruleForm.sort"
            :min="1"
            :max="50"
            size="small"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="ok">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 权限弹框 -->
    <el-dialog
      v-model="dialogFormVisible2"
      :title="formtitle"
      width="500"
      @close="no"
    >
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="dataScope"
        show-checkbox
        default-expand-all
        node-key="value"
        highlight-current
        :props="defaultProps"
        @check="handleCheckChange"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="yes">确认</el-button>
          <el-button @click="no">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Refresh,
  Plus,
  Position,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import {
  rolesPage,
  addData,
  editData,
  delData,
  selData,
  ruleData,
  ruleId,
  ruleMenus,
  ruleTree,
} from "@/api/roleApi";
import { ElTree } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";

const tableData = ref();
const tablenum = ref();
function getData() {
  rolesPage(currentPage4.value, pageSize4.value, formInline.value.user).then(
    (res) => {
      // console.log(res);
      tableData.value = res.data.list;
      tablenum.value = res.data.total;
    }
  );
}
function selects() {
  selData().then((res) => {
    console.log(res);
  });
}
function getTree() {
  ruleTree().then((res) => {
    // console.log(res.data);
    // 递归一下
    dataScope.value = res.data;
    // console.log(dataScope.value);
  });
}
function addId(arr: any) {
  for (var i = 0; i < arr.length; i++) {
    let obj = arr[i];
    obj.id = obj.value;
    if (obj.children) {
      addId(obj.children);
    }
  }
}
onMounted(() => {
  getData();
  // selects();
  getTree();
});

const formInline = ref({
  user: "",
});
// 搜索
const onSubmit = () => {
  // console.log(formInline.value.user);
  getData();
  formInline.value.user = "";
};
// 重置
const reset = () => {
  formInline.value.user = "";
};
// 新增
const adds = () => {
  formtitle.value = "新增角色";
  dialogFormVisible.value = true;
};
// 批量删除
let arrId = ref([]);
const ids = ref("");
const delall = () => {
  // console.log(multipleSelection.value);
  multipleSelection.value.forEach((item) => {
    arrId.value.push(item.id);
  });
  ids.value = arrId.value.join();
  ElMessageBox.confirm("确认删除多条数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delData(ids.value).then((res) => {
        if (res.code == "00000") {
          getData();
          ElMessage({
            type: "success",
            message: "删除成功!",
          });
        }
        arrId.value = [];
        ids.value = "";
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
      arrId.value = [];
      ids.value = "";
    });
};
// 表格
const isdel = ref(true);
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  // console.log(val.length);
  isdel.value = val.length > 0 ? false : true;
};
// 分配权限
const dataScopeArr = ref();
const dataScope = ref();
const scopeId = ref();
const treeRef = ref();
const fenpei = (row: any) => {
  addId(dataScope.value);
  console.log(dataScope.value);
  ruleId(row.id).then((res) => {
    // console.log(res.data);
    dataScopeArr.value = res.data;
    treeRef.value!.setCheckedKeys(res.data, false);
  });

  formtitle.value = "【系统管理员】权限分配";
  dialogFormVisible2.value = true;
  scopeId.value = row.id;
};
// 编辑
const edits = (row: any) => {
  // console.log(row);
  ruleData(row.id).then((res) => {
    // console.log(res.data);
    ruleForm.value = { ...res.data };
  });
  formtitle.value = "修改角色";
  dialogFormVisible.value = true;
};
// 删除
const del = (row: any) => {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // console.log(row.id);
      delData(row.id).then((res) => {
        // console.log(res);
        if (res.code == "00000") {
          getData();
          ElMessage({
            type: "success",
            message: "删除成功!",
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 分页
const currentPage4 = ref(1);
const pageSize4 = ref(5);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`);
  pageSize4.value = val;
  getData();
};
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`);
  currentPage4.value = val;
  getData();
};

// 弹框
const formtitle = ref();
const dialogFormVisible = ref(false);
const dialogFormVisible2 = ref(false);
const ok = () => {
  // 新增
  if (ruleForm.value.name == "" || ruleForm.value.code == "") {
    return ElMessage({ message: "请填写完整信息", type: "warning" });
  }
  if (formtitle.value == "新增角色") {
    // console.log(ruleForm.value);
    addData({ ...ruleForm.value }).then((res) => {
      // console.log(res);
      if (res.code == "00000") {
        getData();
        ElMessage({
          message: "角色信息添加成功！",
          type: "success",
        });
        dialogFormVisible.value = false;
        formtitle.value = "";
        ruleForm.value = {
          id: "",
          name: "",
          code: "",
          status: 1,
          sort: 1,
          createTime: "",
          updateTime: "",
          dataScope: 0,
        };
      }
    });
  }
  // 编辑
  if (formtitle.value == "修改角色") {
    editData(ruleForm.value.id, { ...ruleForm.value }).then((res) => {
      // console.log(res);
      if (res.code == "00000") {
        // console.log(111111111);
        getData();
        ElMessage({
          message: "角色信息修改成功！",
          type: "success",
        });
        dialogFormVisible.value = false;
        formtitle.value = "";
        ruleForm.value = {
          id: "",
          name: "",
          code: "",
          status: 1,
          sort: 1,
          createTime: "",
          updateTime: "",
          dataScope: 0,
        };
      }
    });
  }
};
const cancel = () => {
  dialogFormVisible.value = false;
  formtitle.value = "";
  ruleForm.value = {
    id: "",
    name: "",
    code: "",
    status: 1,
    sort: 1,
    createTime: "",
    updateTime: "",
    dataScope: 0,
  };
};

// 表单
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
interface RuleForm {
  id: string | number;
  name: string;
  code: string;
  status: number;
  sort: number;
  createTime: string;
  updateTime: string;
  dataScope: number;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<RuleForm>({
  id: "",
  name: "",
  code: "",
  status: 1,
  sort: 1,
  createTime: "",
  updateTime: "",
  dataScope: 0,
});
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  dataScope: [{ required: true, message: "请选择权限", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  sort: [{ required: true, message: "请输入序号", trigger: "blur" }],
});

// 权限确认取消
const handleCheckChange = (a, b) => {
  // console.log(b.checkedKeys);
  dataScopeArr.value = b.checkedKeys;
};
const yes = () => {
  ruleMenus(scopeId.value, dataScopeArr.value).then((res) => {
    // console.log(res);
    if (res.code == "00000") {
      ElMessage({
        message: "权限分配成功！",
        type: "success",
      });
      dialogFormVisible2.value = false;
      formtitle.value = "";
      dataScopeArr.value = [];
      getData();
    }
  });
};
const no = () => {
  dialogFormVisible2.value = false;
  formtitle.value = "";
  dataScopeArr.value = [];
};

const defaultProps = {
  children: "children",
  label: "label",
};
</script>

<style scoped>
.demo-form-inline{
  background-color: #fff;
  border-radius: 5px;
  padding-top: 20px;
  padding-left: 15px;
}
</style>